package gcosc.fun.hly.fastsso.service.impl;

import cn.hutool.crypto.SecureUtil;
import gcosc.fun.hly.fastsso.domain.Bo.LoginBo;
import gcosc.fun.hly.fastsso.domain.SsoUser;
import gcosc.fun.hly.fastsso.domain.Vo.LoginUser;
import gcosc.fun.hly.fastsso.result.Code;
import gcosc.fun.hly.fastsso.service.AuthService;
import gcosc.fun.hly.fastsso.service.ISsoRealmService;
import gcosc.fun.hly.fastsso.service.SsoUserService;
import gcosc.fun.hly.fastsso.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final SsoUserService userService;
    private final TokenUtil tokenUtil;
    private final ISsoRealmService realmService;

    @Override
    public boolean isLogin(String token) {
        return tokenUtil.parseToken(token) != null;
    }

    @Override
    public String login(LoginBo loginBo) {
        SsoUser user = userService.getUserByRealmAndUserName(loginBo.getRealm(), loginBo.getUsername());

        if (user == null || !user.getPassword().equals(
                SecureUtil.md5(loginBo.getPassword()))){
            Code.BUSINESS_ERR("用户名或密码错误！");
        }

        LoginUser loginUser = LoginUser.builder().build();

        BeanUtils.copyProperties(user, loginUser);

        String token = tokenUtil.loginUser(loginUser);

        return token;
    }

    @Override
    public LoginUser getLoginUserByToken(String token) {
        LoginUser loginUser = tokenUtil.parseToken(token.split(" ")[1]);
        if (loginUser == null){
            Code.TOKEN_ERR("登录过期");
        }
        return loginUser;
    }

    @Override
    public boolean register(SsoUser ssoUser) {

        if (!realmService.isRealm(ssoUser.getRealm())) {
            Code.BUSINESS_ERR("领域异常");
        }

        return userService.insertByBo(ssoUser);
    }

    @Override
    public boolean logout(String token) {
        return false;
    }

}
